package com.zenithsun.common.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import Decoder.BASE64Decoder;

import com.syzg.core.util.DateUtil;
import com.syzg.webservice.springService.WebServiceI;

/**
 * 文件管理
 * 
 * @author wanglei@enersun.com.cn
 */
public class FileUtil {
	private static Logger log = LoggerFactory.getLogger(FileUtil.class);
	/**
     * 删除空目录
     * @param dir 将要删除的目录路径
     */
	public static void doDeleteEmptyDir(String dir) {
        boolean success = (new File(dir)).delete();
        if (success) {
        	log.info("Successfully deleted empty directory: " + dir);
        } else {
        	log.error("Failed to delete empty directory: " + dir);
        }
    }

    /**
     * 递归删除目录下的所有文件及子目录下所有文件
     * @param dir 将要删除的文件目录
     * @return boolean Returns "true" if all deletions were successful.
     *                 If a deletion fails, the method stops attempting to
     *                 delete and returns "false".
     */
    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            //递归删除目录中的子目录下
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空，可以删除
        return dir.delete();
    }
    
    public static void createDir(String dir){
    	File file = new File(dir);
    	if(!file.exists()){
    		file.mkdir();
    	}
    }
    
    public static String writeFile(String str, String type) {
		String imageFile = "";
		try {
			String path = WebServiceI.class.getClassLoader().getResource("")
					.getPath();
			path = path.substring(0, path.indexOf("WEB-INF"))
					+ "zenithsun/pic/images";
			String subDir = DateUtil.format(new Date(), "yyyy/MMdd");
			String upPath = path + File.separator + subDir;
			createDir(upPath);
			imageFile = upPath +"/"+ new Date().getTime() + "." + type;
			BASE64Decoder decoder = new BASE64Decoder();
			byte[] bytes = decoder.decodeBuffer(str);
			File file = new File(imageFile);
			FileOutputStream fos = new FileOutputStream(file);
			fos.write(bytes);
			fos.flush();
			fos.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String separator = "/images";
		imageFile = imageFile.substring(imageFile.indexOf(separator)
				+ separator.length());
		imageFile = imageFile.replaceAll("\\\\", "/");
		return imageFile;
	}
    /**
     *测试
     */
    public static void main(String[] args) {
        doDeleteEmptyDir("new_dir1");
        String newDir2 = "new_dir2";
        boolean success = deleteDir(new File(newDir2));
        if (success) {
            log.info("Successfully deleted populated directory: " + newDir2);
        } else {
            log.error("Failed to delete populated directory: " + newDir2);
        }     
    }
    
  
}